package com.android.search;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;

import com.android.R;
import com.android.adapters.ItemArrayAdapter;
import com.android.data.ServerManager;
import com.android.entities.Event;

public class SearchEventsActivity extends ListActivity {

	private ProgressDialog m_ProgressDialog = null;
	private Runnable viewItems;
	private static Thread itemsThread;
	private ItemArrayAdapter itemAdapter = null;	 
	ArrayList<Event> listItems = new ArrayList<Event>();	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        
		this.itemAdapter = new ItemArrayAdapter(this, R.layout.row_item, listItems);
		setListAdapter(this.itemAdapter);

        viewItems = new Runnable(){        
            public void run() {
            	retrieveItems();
            }
        };
	    
        itemsThread =  new Thread(null, viewItems, "MagentoBackground");
        	itemsThread.start();
	        m_ProgressDialog = ProgressDialog.show(SearchEventsActivity.this,    
	              "Please wait...", "Retrieving data ...", true);

    }
    
    private void retrieveItems(){
    	try{
    		listItems = ServerManager.getRecommendations();
    		
    	} catch (Exception e) {
            Log.e("BACKGROUND_PROC", e.getMessage());
    	}
    	runOnUiThread(returnRes);
    }
    
    private Runnable returnRes = new Runnable() {

        public void run() {
            if(listItems != null && listItems.size() > 0){
            	itemAdapter.notifyDataSetChanged();
            	
                for(int i = 0; i < listItems.size(); i++) {
                	itemAdapter.add(listItems.get(i));
                }
            }
            m_ProgressDialog.dismiss();
            itemAdapter.notifyDataSetChanged();
            itemsThread.interrupt();
        }
    };

}
